{% extends "./test_base.html" %}

{% block title %}
<title>实验项目信息管理 甲基化检测 甲基化建库信息</title>
{% endblock %}

{% block header_title %}
<h1>甲基化检测 甲基化建库信息</h1>
{% endblock %}

{% block header_ol %}
	<li class="breadcrumb-item"><a href="/Home/">Home</a></li>
	<li class="breadcrumb-item">LIMS</li>
	<li class="breadcrumb-item active">MethyLibraryInfo</li>
{% endblock %}

{% block card-body %}
<table id="table" class="table table-bordered table-hover dt-responsive">
<thead>
<tr id="table_header">

</tr>
</thead>
</table>
{% endblock %}

{% block page-script %}
<script>
  $(document).ready(function () {
      $("#sidebar_LIMS>a").addClass("active");
      $("#sidebar_LIMS").addClass("menu-open");
      $("#sidebar_LIMS>ul>li:eq(0)>a").addClass("active");
      $("#sidebar_LIMS>ul>li:eq(0)>ul>li:eq(0)>a").addClass("active");
      $(".sidebar").removeAttr("hidden");

      let model0 = 'MethyLibraryInfo';
      let url0 = '/api/LIMS/Methy/' + model0 + '/';
      let url1 = '/api/BIS/ExtractInfo/';
      let url2 = '/api/BIS/DNAUsageRecordInfo/';
      let id0 = 0;
      let bulk_update_bool = {% if perms.BIS.bulk_update_MethyLibraryInfo %} true {% else %} false {% endif %};
      let bulk_delete_bool = {% if perms.BIS.bulk_delete_MethyLibraryInfo %} true {% else %} false {% endif %};

      function update_func(e){
          e.preventDefault();
          // 递交前检查，一般是检测model的外键是否存在
          let data1 = $.ajax({
              url: url1, dataType: 'json', contentType: "application/json",
              type: "get", async: false, data: { dna_id: $('#dna_id').val(), fields: "id,sampleinventoryinfo,successM" }
          }).responseJSON[0];
          if (data1 === undefined) {
              $('#myModalError').text('错误！！！核酸提取编号不存在，请填写正确的核酸提取编号。');
              return
          }

          let type = $('#type').val();
          let method = '';
          let url_ajax0 = url0; // MethyLibraryInfo
          let url_ajax1 = url1 + data1.id + '/'; // ExtractInfo
          let url_ajax2 = url2; // DNAUsageRecordInfo
          let send_data0 = $("#modelForm").find(":not(#dna_id)").serialize() + '&' + $.param({
			  extractinfo: data1.id, sampleinventoryinfo: data1.sampleinventoryinfo
          });
          let old_data0;
          if (type === 'new') {
              // new
              method = 'POST';
              // POST前检查，一般是检测model的关键字段值是否存在
              data0 = $.ajax({
                  url: url0, dataType: 'json', contentType: "application/json",
                  type: "get", async: false, data: {singleLB_id: $('#singleLB_id').val(), fields: "id"}
              }).responseJSON[0];
              if (data0 !== undefined) {
                  $('#myModalError').text('错误！！！建库编号已存在，无法添加。如需更新该条目，请在对应行进行更新操作。');
                  return
              }
          } else {
              // edit
              url_ajax0 = url0 + id0 + '/';
              method = 'PUT';
              old_data0 = $.ajax({
                  url: url_ajax0, dataType: 'json', contentType: "application/json",
                  type: "get", async: false, data: {fields: "id,dna_id,usage,mass,singleLB_id"}
              }).responseJSON;
          }

          $.ajax({
              url: url_ajax0,
              method: method,
              data: send_data0,
              headers: {'X-HTTP-Method-Override': 'PATCH'},
              success: function () {
                  let v_tmp = $('#singleLB_id').val();
                  if (type === 'new') {
                      databaseRecordAjaxPut('{{ user.id }}', model0, "单项添加", "建库编号：" + v_tmp);
                      $('#myModalError').text('添加成功！！！建库编号：' + v_tmp);
                      data1.successM = parseFloat(data1.successM) + parseFloat($('#mass').val());
                  } else {
                      databaseRecordAjaxPut('{{ user.id }}', model0, "单项更新", "建库编号：" + v_tmp);
                      $('#myModalError').text('更新成功！！！建库编号：' + v_tmp);
                      data1.successM = parseFloat(data1.successM) + parseFloat($('#mass').val()) -
							  parseFloat(old_data0.mass);
                  }
                  // 修改核酸提取
				  console.info(">>>>url_ajax1: ", url_ajax1);
				  $.ajax({
                      url: url_ajax1,
                      method: 'PATCH',
                      data: $.param({
                          successM: data1.successM
                      }),
                      headers: {'X-HTTP-Method-Override': 'PATCH'},
                      success: function () {
                          databaseRecordAjaxPut('{{ user.id }}', "ExtractInfo", "单项更新", "核酸提取编号：" + data1.sample_id);
                      },
                      error: function (jqXHR, textStatus, errorThrown) {
                          console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                      }
                  });

				  // 添加核酸使用记录
				  $.ajax({
                      url: url_ajax2,
                      method: 'POST',
                      data: $.param({
						  sampleinventoryinfo: data1.sampleinventoryinfo, extractinfo: data1.id,
						  usage_date: $('#LB_date').val(), mass: $('#mass').val(), usage: "建库成功",
						  singleLB_id: $('#singleLB_id').val(), memo: "无"
					  }),
                      headers: {'X-HTTP-Method-Override': 'PATCH'},
                      success: function () {
                          databaseRecordAjaxPut('{{ user.id }}', "DNAUsageRecordInfo", "单项更新", "核酸提取编号：" + data1.sample_id);
                      },
                      error: function (jqXHR, textStatus, errorThrown) {
                          console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
                      }
                  });

                  setTimeout(
                      function () {
                          window.location.reload(true);
                      }, 3000
                  );
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  $('#myModalError').text('出现错误！！！请联系管理员');
                  console.info(url_ajax0, method, send_data0);
                  console.log(jqXHR + ';' + textStatus + ';' + errorThrown)
              }
          });
      }

      function delete_by_id (id_func){
          let url_ajax0 = url0 + id_func + '/';
          let old_data0 = $.ajax({
              url: url_ajax0, dataType: 'json', contentType: "application/json",
              type: "get", async: false, data: {fields: "id,dna_id,usage,mass,singleLB_id"}
          }).responseJSON;
          let res = [];
          $.ajax({
              url: url_ajax0,
              method: 'DELETE',
              success: function () {
                  res.push("success");
                  res.push(id_func);
                  // 更新样本提取表
                  let data1 = $.ajax({
                      url: url1, dataType: 'json', contentType: "application/json",
                      type: "get", async: false, data: { dna_id: old_data0.dna_id, fields: "id,sampleinventoryinfo,successM" }
                  }).responseJSON[0];
                  data1.successM = parseFloat(data1.successM) - parseFloat(old_data0.mass);
                  $.ajax({
                      url: url1 + data1.id + '/',
                      method: 'PATCH',
                      data: $.param({ successM: data1.successM }),
                      headers: {'X-HTTP-Method-Override': 'PATCH'},
                      success: function () {
                          res.push("success");
                          res.push(data1.id);
                      },
                      error: function (jqXHR, textStatus, errorThrown) {
                          res.push("error");
                          res.push(jqXHR + ';' + textStatus + ';' + errorThrown)
                      }
                  });
                  // 更新核酸使用记录
				  let data2 = $.ajax({
                      url: url2, dataType: 'json', contentType: "application/json",
                      type: "get", async: false, data: {singleLB_id: old_data0.singleLB_id}
                  }).responseJSON[0];
				  $.ajax({
					  url: url2 + data2.id + '/',
					  method: 'DELETE',
					  success: function () {
					  	res.push("success");
					  	res.push(data2.id);
					  },
					  error: function (jqXHR, textStatus, errorThrown) {
					  	res.push("error");
					  	res.push(jqXHR + ';' + textStatus + ';' + errorThrown)
					  }
				  });
              },
              error: function (jqXHR, textStatus, errorThrown) {
                  res.push("error");
                  res.push(jqXHR + ';' + textStatus + ';' + errorThrown);
                  res.push("error");
                  res.push(jqXHR + ';' + textStatus + ';' + errorThrown);
                  res.push("error");
                  res.push(jqXHR + ';' + textStatus + ';' + errorThrown);
              }
          });
          return res;
      }

      function delete_func(model0, url0, id0){
          let res = delete_by_id(id0);
        if (res[4] === "success") {
              databaseRecordAjaxPut('{{ user.id }}', "DNAUsageRecordInfo", "单项删除", "id：" + res[5]);
          } else {
              console.log(res[5]);
          }
      	if (res[2] === "success") {
              databaseRecordAjaxPut('{{ user.id }}', "ExtractInfo", "单项更新", "id：" + res[3]);
          } else {
              console.log(res[3]);
          }
          if (res[0] === "success") {
              databaseRecordAjaxPut('{{ user.id }}', model0, "单项删除", "id：" + res[1]);
              window.location.reload(true);
          } else {
              console.log(res[1]);
          }
      }

      function bulkDelete_func(table, model0, url0){
          let arrayLen = table.rows(".selected").data().length;
            if (arrayLen > 0) {
                let id_list0 = [];
                let id_list1 = [];
                let id_list2 = [];
                for (let i = 0; i < arrayLen; i++) {
                    let delete_id = table.rows(".selected").data()[i]['id'];
                    let res = delete_by_id(delete_id);
                    if (res[0] === "success") {
                        id_list0.push(res[1]);
                    }
                    if (res[2] === "success") {
                        id_list1.push(res[3]);
                    }
                    if (res[3] === "success") {
                        id_list2.push(res[3]);
                    }
                }
                databaseRecordAjaxPut('{{ user.id }}', model0, "批量删除", "id_list：[" + id_list0 + "]");
                databaseRecordAjaxPut('{{ user.id }}', "ExtractInfo", "批量更新", "id_list：[" + id_list1 + "]");
                databaseRecordAjaxPut('{{ user.id }}', "DNAUsageRecordInfo", "批量删除", "id_list：[" + id_list2 + "]");
                window.location.reload(true);
            } else {
                $('#bulkDelError').text('没有行被选中，请先选中目标行。');
            }
      }

      let input_params = {
          "title1_text": "甲基化检测 甲基化建库信息 总条目数： ",
		  "fields": [
              // input类型是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, [[value, text]] ]
              // input类型不是select： [ field, name, 是否出现在modal, modal中排序, 是否必填, input类型, value ]
              ["singleLB_id", "建库编号", 1, 1, 1, "text"],
              ["sampler_id", "华大编号", 0],
              ["dna_id", "核酸提取编号", 1, 0, 1, "text"],
              ["tube_id", "管上编号", 1, 2, 0, "text", "无"],
              ["clinical_boolen", "是否临床", 1, 3, 1, "select", [["是", "是"], ["否", "否"]]],
              ["label", "样本标签", 1, 4, 1, "select", [["P", "P"], ["T", "T"],["Frg_gDNA", "Frg_gDNA"]]],
              ["singleLB_name", "文库名", 1, 5, 0, "text", "无"],
              ["barcodes", "index列表", 1, 6, 0, "text", "无"],
              ["LB_date", "建库日期", 1, 7, 1, "date"],
              ["LB_method", "建库方法", 1, 8, 0, "text", "无"],
              ["kit_batch", "试剂批次", 1, 9, 0, "text", "无"],
              ["dna_con", "核酸样本浓度(ug/ul)", 0],
              ["mass", "起始量(ng)", 1, 10, 1, "number_0.001"],
              ["pcr_cycles", "PCR循环数", 1, 11, 0, "number_1", 0],
              ["LB_con", "文库浓度(ng/ul)", 1, 12, 0, "number_0.001", 0],
              ["LB_vol", "文库体积(ul)", 1, 13, 0, "number_0.001", 0],
              ["operator", "操作人", 1, 14, 0, "text", "无"],
              ["memo", "备注", 1, 15, 0, "text", "无"],
              ["last_modify_time", "上次修改时间", 0],
              ["create_time", "创建时间", 0]
          ],
          "update_func": update_func,
          "delete_func": delete_func,
          "bulkDelete_func": bulkDelete_func,
          "download_excel": '/ADVANCE/download_excel/LIMS_' + model0 + '/'
      };
      single_page_generator(model0, url0, id0, bulk_update_bool, bulk_delete_bool, input_params);

      $("#dna_id").blur(function () {
          $("#singleLB_id").val($("#dna_id").val()+"_m1");
      });
  });
</script>
{% endblock %}
